<template>
  <div
    class="etf-activity"
    :class="etfActivityData.buttonType === '2' ? 'transfer-box' : 'rest-box'"
  >
    <div v-for="(item, index) in imgArr" :key="index">
      <img
        v-if="index === 3 ? etfActivityData.isShowImg2 === '1' : true"
        v-lazy="item?.urlName"
        :alt="item?.altName"
      />
    </div>
    <div class="etf-button">
      <div v-if="etfActivityData.buttonType === '2'" class="condition">
        预约条件:
        <span class="spa">普通账户资产达1万(含)</span>
        我的资产:
        <span>{{ etfActivityData.asset ?? "0" }}元</span>
      </div>
      <Button
        class="subscribe"
        :loading="loading"
        loading-text="加载中..."
        :disabled="etfActivityData.buttonStatus === '2' || isInAppBtn"
        :color="
          etfActivityData.buttonStatus === '2' || isInAppBtn
            ? '#D7DAE1'
            : 'linear-gradient(270deg, #fec031 0%, #ff8b0d 100%)'
        "
        @click="handleBtn"
      >
        {{ etfActivityData.buttonName }}
        <p v-if="etfActivityData.buttonType === '2'" class="tip">（请在交易时间完成转账）</p>
      </Button>
    </div>
    <!-- <div :class="etfActivityData.buttonType === '2' ? 'TransferBox' : 'restBox'"></div> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { storeToRefs } from "pinia";
import { Button } from "vant";
import {
  checkImgExists,
  getClientInfo,
  navigateToWithAccount,
  openWebview,
  shareNewsUrl,
  pageView,
  pageDuration,
  pageIconClick,
} from "@/utils";
import { isInApp, changeUrl } from "@ret-utils/bridge";
import { useEtfActivityStore } from "@/stores/etf-activity";
import { ETF_ACTIVITY_TITLE } from "@/consts";

const router = useRouter();
const route = useRoute();
const etfActivityStore = useEtfActivityStore();
const { etfActivityData, loading } = storeToRefs(etfActivityStore);
const { fundAccount } = getClientInfo();
const baseURL = import.meta.env.VITE_BASE_URL;
const sensorsStartTime = ref(0); // 开始时间
const sensorsEndTime = ref(0); // 结束时间
const imgArr = [
  {
    urlName: "etf1.png",
    altName: "ETF介绍",
  },
  {
    urlName: "etf2.png",
    altName: "指数投资",
  },
  {
    urlName: `${baseURL}/ret-activity-server/imgs/etfCombi/img1.png?time=${new Date().getTime()}`,
    altName: "如何收费",
  },
  {
    urlName: `${baseURL}/ret-activity-server/imgs/etfCombi/img2.png?time=${new Date().getTime()}`,
    altName: "先行者",
  },
  {
    urlName: `${baseURL}/ret-activity-server/imgs/etfCombi/img3.png?time=${new Date().getTime()}`,
    altName: "风险提示",
  },
];

let isFundAccount: any = ref("");
onBeforeMount(() => {
  getUserEtfActivity(fundAccount as string);
  sensorsStartTime.value = Number(new Date());
  pageView({
    page_title: ETF_ACTIVITY_TITLE,
    Page_from: route.query.Page_from || "",
    is_Operactmainpage: "1",
    is_login: false,
    is_accountlogin: false,
  });
});

let isInAppBtn = ref(false);
onMounted(() => {
  // 调用原生返回页面就会调用 GoBackOnLoad 方法
  (window as any).GoBackOnLoad = onGoBackOnLoad;
  // 挂载window让客户端调用-分享
  (window as any).shareDetailContent = onToShare;
  if (isInApp()) {
    isInAppBtn.value = false;
  } else {
    isInAppBtn.value = true;
  }
  console.log("onMounted", fundAccount, isInAppBtn.value);
});

onBeforeUnmount(() => {
  sensorsEndTime.value = Number(new Date());
  pageDuration({
    page_title: ETF_ACTIVITY_TITLE,
    is_login: false,
    event_duration: (sensorsEndTime.value - sensorsStartTime.value) / 1000,
  });

  (window as any).GoBackOnLoad = () => {};
  (window as any).shareDetailContent = () => {};
});

// 唤起登录返回到此页面触发onload重新获取用户信息
const onGoBackOnLoad = () => {
  const { fundAccount } = getClientInfo(route);
  console.log(fundAccount, "唤起登录返回到此页面触发onload");
  getUserEtfActivity(fundAccount as string);
};

const onToShare = () => {
  shareNewsUrl(
    import.meta.env.VITE_ETF_SHARE_URL,
    "《接招！ETF》666个永久免费签约资格限时送！",
    "ETF投资，咬定青山还是待时而动？敬请接招！"
  );
  pageIconClick({
    mainpage_icon_section: "顶部",
    mainpage_icon_name: "点击分享-炫耀一下",
    mainpage_icon_index: "1",
  });
};

const getUserEtfActivity = (fundAccount: string) => {
  if (fundAccount) {
    etfActivityStore.getLogInEtfActivity();
    isFundAccount.value = fundAccount;
  } else {
    etfActivityStore.getNotLogEtfActivity();
  }
  console.log(fundAccount, isFundAccount.value, "fundAccount123");
};

const handleBtn = async () => {
  console.log(
    isFundAccount.value,
    etfActivityData.value.buttonType,
    etfActivityData.value?.buttonName,
    "点击底部按钮"
  );
  // 活动埋点
  pageIconClick({
    mainpage_icon_section: "底部",
    mainpage_icon_name: etfActivityData.value?.buttonName,
    mainpage_icon_index: "1",
  });
  // 去看看
  if (etfActivityData.value.buttonType === "3") {
    changeUrl(etfActivityData.value.prodUrl as string);
    return;
  }
  if (!isFundAccount.value) {
    // `http://action:10061/?fullscreen=1&&firsttype=10&&secondtype=9&&url=${
    //     import.meta.env.VITE_ETF_SHARE_URL
    //   }`
    navigateToWithAccount();
    return;
  }
  // 去转帐
  if (etfActivityData.value.buttonType === "2") {
    openWebview("/jynew/dcgyh3.0/dcg_index.html?fromPageName=“接招！ETF”服务");
    return;
  }
  // 预约
  if (etfActivityData.value.buttonType === "1") {
    await etfActivityStore.getLogInEtSubscribe();
    let reserveSort = JSON.parse(localStorage.getItem("reserveSort") as string);
    if (reserveSort) {
      if (isInApp()) {
        openWebview(import.meta.env.VITE_ETF_TICKET_URL);
      } else {
        router.push({ path: "/etf-free-ticket" });
      }
    }
  }
};
</script>

<style lang="less" src="./assets/etf-subscribe.less" scoped></style>
